<?php

namespace app\api\controller;

use app\api\logic\CrmSettingsLogic;
use app\common\basic\BaseController;
use app\common\logic\SystemRegionLogic;
use app\common\model\Company;
use app\common\model\SystemUser;
use app\common\service\SystemDictService;
use support\Request;
use support\Response;

class ApiController extends BaseController

{
    /**
     * 获取分组及其字段结构
     * @param Request $request
     * @return Response
     */
    public function getFieldGroups(Request $request): Response
    {
        $logic = new CrmSettingsLogic();
        $groups = $logic->getGroupsWithFields();
        return $this->success ($groups);
    }
    
    /**
     * 获取验证规则
     * @param Request $request
     * @return Response
     */

    public function getValidationRules(Request $request) {
        $rules = SystemDictService::getDictData('validation_rule');
        return $this->success($rules);
    }

    /**
     * 地区信息
     */
    public function getRegion(Request $request)
    {
        $regionLogic = new SystemRegionLogic();
        $where = $request->more([
            ['name', ''],
            ['parent_id', 0],
        ]);
        $isTree = $request->input('tree', 'false');
        if ($isTree === 'true') {
            unset($where['parent_id']);
            return $this->success($regionLogic->tree($where));
        }
        if (empty($where['parent_id'])) {
            $where['parent_id'] = 0;
        }
        $data = $regionLogic->getAllRegion($where);
        foreach($data as &$item) {
            if ($item['level'] < 4)
                $item['hasChildren'] = $regionLogic->search(['parent_id' => $item['id']])->count() > 0 ? 1 : 0;
            else
                $item['hasChildren'] = 0;
            
        }
        return $this->success($data);
    }
    
    /**
     * 用户列表
     * @param Request $request
     */
    public function getUserList(Request $request) {
        $where = $request->more([
            ['status', ''],
            ['dept_id', ''],
            ['post_id', ''],
            ['role_id', ''],
            ['nickname', '']
        ]);

        $withSearch = array_keys($where);
        $data = $where;
        foreach ($withSearch as $k => $v) {
            if ($data[$v] === '') {
                unset($data[$v]);
                unset($withSearch[$k]);
            }
        }
        $userModel = new SystemUser();
        $query = $userModel->whereNull('delete_time')->withSearch($withSearch, $where);
        
        return $this->success($query->field('id, avatar, nickname, username, status, dept_id')->select()->toArray());
    }
    
    public function getCompanyProfit(Request $request)
    {
        $id = $request->input('company_id');
        $model = new Company();
        $info = $model->where('id', $id)->find();
        if (empty($info)) {
            return $this->fail('公司不存在');
        }
        return $this->success($info->toArray());
    }
}